﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Web;

namespace Woddle.Core
{
    // 请求方式定义
    public enum RequestType
    {
        EN_GET,
        EN_POST
    }

    // 请求基本信息定义
    public class RequestInfo
    {
        #region 成员变量定义
        // URL
        string strURL;
        // 请求类型
        string strAccept = @"*/*";
        // 代理
        string strUserAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
        // 引用
        string strReferer = @"https://kyfw.12306.cn/";
        // 请求方式
        RequestType requstType = RequestType.EN_GET;
        // 连接在线
        String strConnect = "";
        #endregion

        #region 属性定义
        public string URL
        {
            get { return strURL; }
            set { strURL = value; }
        }

        public string Accept
        {
            get { return strAccept; }
            set { strAccept = value; }
        }

        public string UserAgent
        {
            get { return strUserAgent; }
            set { strUserAgent = value; }
        }

        public string Referer
        {
            get { return strReferer; }
            set { strReferer = value; }
        }

        public RequestType Method
        {
            get { return requstType; }
            set { requstType = value; }
        }
        public string Connect
        {
            get { return strConnect; }
            set { strConnect = value; }
        }

        #endregion

        /// <summary>
        /// 返回一个对象
        /// </summary>
        /// <returns></returns>
        public HttpWebRequest GetRequestInstance()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);


            request.Accept = strAccept;


            request.UserAgent = strUserAgent;


            request.Referer = strReferer;

            switch (requstType)
            {
                case RequestType.EN_GET:
                    request.Method = "GET";
                    break;
                case RequestType.EN_POST:
                    request.Method = "POST";
                    break;
            }
            return request;
        }
    }

    public class HttpHelper
    {
        /// <summary>
        /// Get方式获取返回的字符串，一般未json字符串
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <param name="cookie"></param>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string GetRequestStr(RequestInfo requestInfo, CookieContainer cookie, string strParam = "")
        {
            // 创建一个请求
            if (requestInfo == null)
            {
                return "";
            }
            requestInfo.URL += strParam;
            HttpWebRequest request = requestInfo.GetRequestInstance();
            request.Method = "GET";
            request.CookieContainer = cookie;
            request.ServicePoint.ConnectionLimit = int.MaxValue;

            // 请求数据
            string strData = "";
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strData = reader.ReadToEnd();
                    }
                }
            }
            catch (System.Exception ex)
            {
                return "";
            }
            
            // 返回数据
            return strData;
        }

        /// <summary>
        /// Get方式获取返回的图像
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <param name="cookie"></param>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static Image GetRespondImg(RequestInfo requestInfo, CookieContainer cookie, string strParam = "")
        {
            // 创建一个请求
            if (requestInfo == null)
            {
                return null;
            }
            requestInfo.URL += strParam;
            HttpWebRequest request = requestInfo.GetRequestInstance();
            request.Method = "GET";
            request.CookieContainer = cookie;
            request.ServicePoint.ConnectionLimit = int.MaxValue;

            // 请求数据
            Image imgData = null;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        imgData = Image.FromStream(stream);
                    }
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }

            // 返回数据
            return imgData;
        }


        /// <summary>
        /// 提交订单数据, 含有中文的需要转换URL.ENCODING转
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <param name="cookie"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string PostWebContent(RequestInfo requestInfo, CookieContainer cookie, string param)
        {
            byte[] bs = Encoding.ASCII.GetBytes(param);

            // 创建一个POST请求
            if (requestInfo == null)
            {
                return null;
            }
            HttpWebRequest request = requestInfo.GetRequestInstance();
            request.CookieContainer = cookie;
            request.ServicePoint.ConnectionLimit = int.MaxValue;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bs.Length;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            // 发送请求
            var httpWebResponse = (HttpWebResponse)request.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            string html = streamReader.ReadToEnd();

            streamReader.Close();
            responseStream.Close();

            request.Abort();
            httpWebResponse.Close();

            return html;
        }

        /// <summary>
        /// 编码URL地址
        /// </summary>
        /// <param name="str"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string URLEncoding(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 解码URL地址
        /// </summary>
        /// <param name="str"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string URLDecodeing(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// UTS时间变成一般时间
        /// </summary>
        /// <param name="unixTimeStamp"></param>
        /// <returns></returns>
        public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            // 定义其实时间
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }

    }
}
